{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "nbsphinx": "hidden"
   },
   "source": [
    "[Index](Index.ipynb) - [Back](Output Widget.ipynb) - [Next](Widget Styling.ipynb)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Widget Events"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Special events"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `Button` is not used to represent a data type.  Instead the button widget is used to handle mouse clicks.  The `on_click` method of the `Button` can be used to register function to be called when the button is clicked.  The doc string of the `on_click` can be seen below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ipywidgets as widgets\n",
    "print(widgets.Button.on_click.__doc__)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### Example"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since button clicks are stateless, they are transmitted from the front-end to the back-end using custom messages.  By using the `on_click` method, a button that prints a message when it has been clicked is shown below. To capture `print`s (or any other kind of output) and ensure it is displayed, be sure to send it to an `Output` widget (or put the information you want to display into an `HTML` widget)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from IPython.display import display\n",
    "button = widgets.Button(description=\"Click Me!\")\n",
    "output = widgets.Output()\n",
    "\n",
    "display(button, output)\n",
    "\n",
    "def on_button_clicked(b):\n",
    "    with output:\n",
    "        print(\"Button clicked.\")\n",
    "\n",
    "button.on_click(on_button_clicked)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Traitlet events"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Widget properties are IPython traitlets and traitlets are eventful.  To handle  changes, the `observe` method of the widget can be used to register a callback.  The doc string for `observe` can be seen below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(widgets.Widget.observe.__doc__)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### Signatures"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Mentioned in the doc string, the callback registered must have the signature `handler(change)` where `change` is a dictionary holding the information about the change. \n",
    "\n",
    "Using this method, an example of how to output an `IntSlider`'s value as it is changed can be seen below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "int_range = widgets.IntSlider()\n",
    "output2 = widgets.Output()\n",
    "\n",
    "display(int_range, output2)\n",
    "\n",
    "def on_value_change(change):\n",
    "    with output2:\n",
    "        print(change['new'])\n",
    "\n",
    "int_range.observe(on_value_change, names='value')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Linking Widgets"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Often, you may want to simply link widget attributes together. Synchronization of attributes can be done in a simpler way than by using bare traitlets events. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Linking traitlets attributes in the kernel\n",
    "\n",
    "The first method is to use the `link` and `dlink` functions from the `traitlets` module (these two functions are re-exported by the `ipywidgets` module for convenience). This only works if we are interacting with a live kernel."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "caption = widgets.Label(value='The values of slider1 and slider2 are synchronized')\n",
    "sliders1, slider2 = widgets.IntSlider(description='Slider 1'),\\\n",
    "                    widgets.IntSlider(description='Slider 2')\n",
    "l = widgets.link((sliders1, 'value'), (slider2, 'value'))\n",
    "display(caption, sliders1, slider2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "caption = widgets.Label(value='Changes in source values are reflected in target1')\n",
    "source, target1 = widgets.IntSlider(description='Source'),\\\n",
    "                  widgets.IntSlider(description='Target 1')\n",
    "dl = widgets.dlink((source, 'value'), (target1, 'value'))\n",
    "display(caption, source, target1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Function `traitlets.link` and `traitlets.dlink` return a `Link` or `DLink` object. The link can be broken by calling the `unlink` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "l.unlink()\n",
    "dl.unlink()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Registering callbacks to trait changes in the kernel\n",
    "\n",
    "Since attributes of widgets on the Python side are traitlets, you can register handlers to the change events whenever the model gets updates from the front-end.\n",
    "\n",
    "The handler passed to observe will be called with one change argument. The change object holds at least a `type` key and a `name` key, corresponding respectively to the type of notification and the name of the attribute that triggered the notification.\n",
    "\n",
    "Other keys may be passed depending on the value of `type`. In the case where type is `change`, we also have the following keys:\n",
    "\n",
    "- `owner` : the HasTraits instance\n",
    "- `old` : the old value of the modified trait attribute\n",
    "- `new` : the new value of the modified trait attribute\n",
    "- `name` : the name of the modified trait attribute."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "caption = widgets.Label(value='The values of range1 and range2 are synchronized')\n",
    "slider = widgets.IntSlider(min=-5, max=5, value=1, description='Slider')\n",
    "\n",
    "def handle_slider_change(change):\n",
    "    caption.value = 'The slider value is ' + (\n",
    "        'negative' if change.new < 0 else 'nonnegative'\n",
    "    )\n",
    "\n",
    "slider.observe(handle_slider_change, names='value')\n",
    "\n",
    "display(caption, slider)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Linking widgets attributes from the client side"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When synchronizing traitlets attributes, you may experience a lag because of the latency due to the roundtrip to the server side. You can also directly link widget attributes in the browser using the link widgets, in either a unidirectional or a bidirectional fashion.\n",
    "\n",
    "Javascript links persist when embedding widgets in html web pages without a kernel."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "caption = widgets.Label(value='The values of range1 and range2 are synchronized')\n",
    "range1, range2 = widgets.IntSlider(description='Range 1'),\\\n",
    "                 widgets.IntSlider(description='Range 2')\n",
    "l = widgets.jslink((range1, 'value'), (range2, 'value'))\n",
    "display(caption, range1, range2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "caption = widgets.Label(value='Changes in source_range values are reflected in target_range1')\n",
    "source_range, target_range1 = widgets.IntSlider(description='Source range'),\\\n",
    "                              widgets.IntSlider(description='Target range 1')\n",
    "dl = widgets.jsdlink((source_range, 'value'), (target_range1, 'value'))\n",
    "display(caption, source_range, target_range1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Function `widgets.jslink` returns a `Link` widget. The link can be broken by calling the `unlink` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# l.unlink()\n",
    "# dl.unlink()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The difference between linking in the kernel and linking in the client\n",
    "\n",
    "Linking in the kernel means linking via python. If two sliders are linked in the kernel, when one slider is changed the browser sends a message to the kernel (python in this case) updating the changed slider, the link widget in the kernel then propagates the change to the other slider object in the kernel, and then the other slider's kernel object sends a message to the browser to update the other slider's views in the browser. If the kernel is not running (as in a static web page), then the controls will not be linked.\n",
    "\n",
    "Linking using jslink (i.e., on the browser side) means contructing the link in Javascript. When one slider is changed, Javascript running in the browser changes the value of the other slider in the browser, without needing to communicate with the kernel at all. If the sliders are attached to kernel objects, each slider will update their kernel-side objects independently.\n",
    "\n",
    "To see the difference between the two, go to the [static version of this page in the ipywidgets documentation](http://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Events.html) and try out the sliders near the bottom. The ones linked in the kernel with `link` and `dlink` are no longer linked, but the ones linked in the browser with `jslink` and `jsdlink` are still linked."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Continuous updates\n",
    "\n",
    "Some widgets offer a choice with their `continuous_update` attribute between continually updating values or only updating values when a user submits the value (for example, by pressing Enter or navigating away from the control). In the next example, we see the \"Delayed\" controls only transmit their value after the user finishes dragging the slider or submitting the textbox. The \"Continuous\" controls continually transmit their values as they are changed. Try typing a two-digit number into each of the text boxes, or dragging each of the sliders, to see the difference."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = widgets.IntSlider(description=\"Delayed\", continuous_update=False)\n",
    "b = widgets.IntText(description=\"Delayed\", continuous_update=False)\n",
    "c = widgets.IntSlider(description=\"Continuous\", continuous_update=True)\n",
    "d = widgets.IntText(description=\"Continuous\", continuous_update=True)\n",
    "\n",
    "widgets.link((a, 'value'), (b, 'value'))\n",
    "widgets.link((a, 'value'), (c, 'value'))\n",
    "widgets.link((a, 'value'), (d, 'value'))\n",
    "widgets.VBox([a,b,c,d])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Sliders, `Text`, and `Textarea` controls default to `continuous_update=True`. `IntText` and other text boxes for entering integer or float numbers default to `continuous_update=False` (since often you'll want to type an entire number before submitting the value by pressing enter or navigating out of the box)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Debouncing\n",
    "\n",
    "When trait changes trigger a callback that performs a heavy computation, you may want to not do the computation as often as the value is updated. For instance, if the trait is driven by a slider which has its `continuous_update` set to `True`, the user will trigger a bunch of computations in rapid succession.\n",
    "\n",
    "Debouncing solves this problem by delaying callback execution until the value has not changed for a certain time, after which the callback is called with the latest value. The effect is that the callback is only called when the trait pauses changing for a certain amount of time.\n",
    "\n",
    "Debouncing can be implemented using an asynchronous loop or threads. We show an asynchronous solution below, which is more suited for ipywidgets. If you would like to instead use threads to do the debouncing, replace the `Timer` class with `from threading import Timer`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import asyncio\n",
    "\n",
    "class Timer:\n",
    "    def __init__(self, timeout, callback):\n",
    "        self._timeout = timeout\n",
    "        self._callback = callback\n",
    "        self._task = asyncio.ensure_future(self._job())\n",
    "\n",
    "    async def _job(self):\n",
    "        await asyncio.sleep(self._timeout)\n",
    "        self._callback()\n",
    "\n",
    "    def cancel(self):\n",
    "        self._task.cancel()\n",
    "\n",
    "def debounce(wait):\n",
    "    \"\"\" Decorator that will postpone a function's\n",
    "        execution until after `wait` seconds\n",
    "        have elapsed since the last time it was invoked. \"\"\"\n",
    "    def decorator(fn):\n",
    "        timer = None\n",
    "        def debounced(*args, **kwargs):\n",
    "            nonlocal timer\n",
    "            def call_it():\n",
    "                fn(*args, **kwargs)\n",
    "            if timer is not None:\n",
    "                timer.cancel()\n",
    "            timer = Timer(wait, call_it)\n",
    "        return debounced\n",
    "    return decorator"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is how we use the `debounce` function as a decorator. Try changing the value of the slider. The text box will only update after the slider has paused for about 0.2 seconds."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "slider = widgets.IntSlider()\n",
    "text = widgets.IntText()\n",
    "\n",
    "@debounce(0.2)\n",
    "def value_changed(change):\n",
    "    text.value = change.new\n",
    "slider.observe(value_changed, 'value')\n",
    "\n",
    "widgets.VBox([slider, text])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Throttling\n",
    "\n",
    "Throttling is another technique that can be used to limit callbacks. Whereas debouncing ignores calls to a function if a certain amount of time has not passed since the last (attempt of) call to the function, throttling will just limit the rate of calls. This ensures that the function is regularly called.\n",
    "\n",
    "We show an synchronous solution below. Likewise, you can replace the `Timer` class with `from threading import Timer` if you want to use threads instead of asynchronous programming."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import asyncio\n",
    "from time import time\n",
    "\n",
    "def throttle(wait):\n",
    "    \"\"\" Decorator that prevents a function from being called\n",
    "        more than once every wait period. \"\"\"\n",
    "    def decorator(fn):\n",
    "        time_of_last_call = 0\n",
    "        scheduled = False\n",
    "        new_args, new_kwargs = None, None\n",
    "        def throttled(*args, **kwargs):\n",
    "            nonlocal new_args, new_kwargs, time_of_last_call, scheduled\n",
    "            def call_it():\n",
    "                nonlocal new_args, new_kwargs, time_of_last_call, scheduled\n",
    "                time_of_last_call = time()\n",
    "                fn(*new_args, **new_kwargs)\n",
    "                scheduled = False\n",
    "            time_since_last_call = time() - time_of_last_call\n",
    "            new_args = args\n",
    "            new_kwargs = kwargs\n",
    "            if not scheduled:\n",
    "                new_wait = max(0, wait - time_since_last_call)\n",
    "                Timer(new_wait, call_it)\n",
    "                scheduled = True\n",
    "        return throttled\n",
    "    return decorator"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To see how different it behaves compared to the debouncer, here is the same slider example with its throttled value displayed in the text box. Notice how much more interactive it is, while still limiting the callback rate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "slider = widgets.IntSlider()\n",
    "text = widgets.IntText()\n",
    "\n",
    "@throttle(0.2)\n",
    "def value_changed(change):\n",
    "    text.value = change.new\n",
    "slider.observe(value_changed, 'value')\n",
    "\n",
    "widgets.VBox([slider, text])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "nbsphinx": "hidden"
   },
   "source": [
    "[Index](Index.ipynb) - [Back](Output Widget.ipynb) - [Next](Widget Styling.ipynb)"
   ]
  }
 ],
 "metadata": {
  "cell_tags": [
   [
    "<None>",
    null
   ]
  ],
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
